package cn.example.practice.servlet;

import cn.example.practice.model.User;
import cn.example.practice.db.ShopCartDao;
import cn.example.practice.model.CartItem;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.List;

@WebServlet("/toShopCartServlet")
public class ToShopCartServlet extends HttpServlet {
    private final ShopCartDao shopCartDao = new ShopCartDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("loginUser");
        List<CartItem> cartItems = shopCartDao.getCartItems(user.getId());
        request.setAttribute("cartItems", cartItems);

        // 计算总金额
        double total = cartItems.stream()
                .mapToDouble(CartItem::getTotal)
                .sum();
        request.setAttribute("total", total);

        request.getRequestDispatcher("/WEB-INF/jsp/shop_cart.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
